//
//  LLOAuthViewController.swift
//  新浪微博
//
//  Created by mac on 16/5/23.
//  Copyright © 2016年 mac.com. All rights reserved.
//

import UIKit
import SVProgressHUD
private let userInfor = "com.itheima.userInfoKey"
class LLOAuthViewController: UIViewController ,UIWebViewDelegate{
    let webview = UIWebView()
    override func loadView() {
        view = webview
        webview.delegate = self
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavbar()
        loadOAuthPage()
    }
}
extension LLOAuthViewController {
        @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        }
        @objc private func testAccount(){
        let jsString = "document.getElementById('userId').value ='18247255318',document.getElementById('passwd').value = '5056888521521lmz' "
        webview.stringByEvaluatingJavaScriptFromString(jsString)
        }
    private func setNavbar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: Selector("close"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户", target: self, action: Selector("testAccount"))
    
    }
    private func loadOAuthPage(){
     let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)!
        let req = NSURLRequest (URL: url)
        webview.loadRequest(req)
    
    }
    
}
extension LLOAuthViewController {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString ?? ""
        let successFlag = "code="
        if  urlString.containsString(successFlag){
            let range = urlString.rangeOfString(successFlag)!
            let code = urlString.substringFromIndex(range.endIndex)
            print(code,urlString)
            
            //获取code 之后 应该使用 code码 请求token(用户访问令牌)
            //            loadAccessToken(code)
            LLUserAccountViewModel.sharedAccountViewModel.loadAccenToken(code, finished: { (isSuccess) -> () in
                if !isSuccess{
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    print("token信息请求失败")
                    return
                }
                //不加载网页
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)


            })
            return false

       }
                return true
      }
}